<?php
/**
 * Created by PhpStorm.
 * User: luoqinghui
 * Date: 2020/7/24
 * Time: 上午17:40
 */

namespace App\Http\Controllers\Api\System;

use App\Http\Controllers\Controller;
use App\Modules\System\Services\SetMedicinalService;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

/**
 * 当前用药设置
 */
class SetMedicinalController extends Controller{
    /**
     * 当前用药列表
     */
    public function getList(){
        $user_id = $this->getLoginUser()->id;
        $result = SetMedicinalService::getList(['user_id'=>$user_id]);
        return response()->success($result);
    }

    /**
     * 当前用药设置
     */
    public function updateSetMedicinal(Request $request){
        $user_id = $this->getLoginUser()->id;
//        $user_id = 1;
        $dataJson = $request->input('data');
        if ( empty($dataJson) ) return response()->error("PARAM_EMPTY");
        $dataArr = json_decode($dataJson,true);
        $compareArr = [1,2,3,4];
        //判断参数是否正确，一个用户最多添加2个胰岛素。参数有id是修改。没有id是添加。判断当前参数添加的个数
        $addNum = 0;
        foreach ( $dataArr as $key => $value ) {
            $itemArr = array_column($value,'meals');
            sort($itemArr);
            if ( $compareArr != $itemArr || empty($value[0]) ) {
                return response()->error("PARAM_ERROR");
            }
            if ( empty($value[0]['id']) ) {
                $addNum += 1;
            }
        }
        //查询当前用户是否有数据
        $result = SetMedicinalService::getCount(['user_id'=>$user_id,'fields'=>'medicinal_id']);
        if ( $addNum+count($result) > 2 ) return response()->error("PARAM_ERROR");  //判断用户是否已经添加过两种胰岛素
        DB::beginTransaction();
        try{
            foreach ( $dataArr as $key => $value ) {
                foreach ( $value as $k => $v ) {
                    //没有id为添加,有id为修改
                    if ( empty($v['id']) ) {
                        $v['user_id'] = $user_id;
                        $result = SetMedicinalService::addSetMedicinal($v);
                    }else{
                        $result = SetMedicinalService::updateSetMedicinal($v);
                    }
                    if ( empty($result) && $result !== 0 ) throw new \Exception('ADD_FAILURE');
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->error($e->getMessage());
        }
        return response()->success();
    }
}